Shiny.addCustomMessageHandler("scatterplot_values", function(message) {

    var dataset = message;

    var parseTime = d3.timeParse("%H%M");
    var formatTime = d3.timeFormat("%H:%M");

    for (i = 0; i < dataset.length; i++) {
        dataset[i][0] = parseTime(dataset[i][0]);
    }

    /*var margin = {top: 20, right: 50, bottom: 50, left: 85},
        width = window.innerWidth * 0.8,
        height = window.innerHeight * 0.8,
        plot_width = width - margin.right - margin.left,
        plot_height = height - margin.top - margin.bottom;*/

    var scatterplot = d3.select("#scatterplot_area")
        .append("svg")
        .attr("width", width)
        .attr("height", height);

    var brush = d3.polybrush()
        .x(d3.scaleLinear().range([margin.left / 2, width]))
        .y(d3.scaleLinear().range([margin.top / 2, height]))
        .on("start", function() {
    	scatterplot.selectAll(".selected").classed("selected", false);
        })
        .on("brush", highlightBrushedPoints)
        .on("end", displayTable);
    scatterplot.append("g")
        .attr("class", "brush")
        .call(brush);

    function clearTableRows() {

        hideTableColNames();
        d3.selectAll(".row_data").remove();
    }

    function hideTableColNames() {
        d3.select("table").style("visibility", "hidden");
    }

    function showTableColNames() {
        d3.select("table").style("visibility", "visible");
    }

    function highlightBrushedPoints() {

        scatterplot.selectAll(".point").classed("selected", function(d) {
            //get the associated circle
            var id = d3.select(this).attr("id");
            var i = id.substr(id.indexOf("-") + 1, id.length);

            if (brush.isWithinExtent(xScale(d[0]), yScale(d[1]))) {
                return true;
            } else {
                return false;
            }
        });
    }

    function displayTable() {

        var d_brushed =  d3.selectAll(".point.selected").data();

        // populate table if one or more elements is brushed
        if (d_brushed.length > 0) {
    	clearTableRows();
    	d_brushed.forEach(d_row => populateTableRow(d_row));
        } else {
    	clearTableRows();
        }
    }

    function populateTableRow(d_row) {

        showTableColNames();

        var d_row_filter = [d_row[2], // Agente Causador
                            formatTime(d_row[0]), // Hora
                            d_row[1]]; //Idade

        d3.select("table")
            .append("tr")
            .attr("class", "row_data")
            .selectAll("td")
            .data(d_row_filter)
            .enter()
            .append("td")
            .attr("align", (d, i) => i == 0 ? "left" : "right")
            .text(d => d);
    }
    var xScale = d3.scaleTime()
        .domain(d3.extent(dataset, function(d) { return (d[0]); }))
        .range([margin.left, plot_width]);

    var yScale = d3.scaleLinear()
        .domain(d3.extent(dataset, function(d) { return d[1]; }))
        .range([plot_height, margin.top]);
    var axis_x = d3.axisBottom(xScale)
        .tickFormat(formatTime);
    var axis_y = d3.axisLeft(yScale);
    var points = scatterplot.append("g").attr("id", "points");

    // Criar círculos
    points.selectAll("circle")
        .data(dataset)
        .enter()
        .append("circle")
        .attr("class", "point")
        .attr("id", function(d, i) {
    	return "point-" + i;
        })
        .attr("r", 3)
        .attr("cx", function(d) {
    	return xScale(d[0]);
        })
        .attr("cy", function(d) {
    	return yScale(d[1]);
        });
    scatterplot.append("g")
        .attr("id", "axis_x")
        .attr("transform", "translate(0," + (plot_height + margin.bottom / 2) + ")")
        .call(axis_x);

    scatterplot.append("g")
        .attr("id", "axis_y")
        .attr("transform", "translate(" + (margin.left / 2) + ", 0)")
        .call(axis_y);

    d3.select("#axis_x")
        .append("text")
        .attr("transform", "translate(420, -5)")
        .text("Hora");

    d3.select("#axis_y")
        .append("text")
        .attr("transform", "rotate(-90) translate(-20, 15)")
        .text("Idade");

});
